//
//  VideoViewController.m
//  ioshuanwu
//
//  Created by 幻音 on 15/12/28.
//  Copyright © 2015年 幻音. All rights reserved.
//

#import "VideoViewController.h"
#import "FullViewController.h"
#import "CommitTableViewCell.h"
#import "AFNetworking.h"
#import "DataModel.h"
#import "Model.h"
#define kRandomColor [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]
@interface VideoViewController ()<FMGVideoPlayViewDelegate,UITableViewDelegate,UITableViewDataSource>

/* 全屏控制器 */
@property (nonatomic, strong) FullViewController *fullVc;

@property (nonatomic, assign) BOOL isShowDanmak;

@property (nonatomic, strong) UIButton *backBtn;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UITextField *textField;

@property (nonatomic, strong) UIButton *commentBtn;
@end

@implementation VideoViewController


+ (instancetype)shareVideoController
{
    static VideoViewController * video = nil;
    static dispatch_once_t token;
    if (video == nil) {
        dispatch_once(&token, ^{
            video = [[VideoViewController alloc] init];
        });
    }
    return video;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.playView.urlString != _video.mp4_url) {
        [_playView setUrlString:_video.mp4_url];
        [_playView.player play];
        // 视图将要出现播放
        _playView.playOrPauseBtn.selected = YES;
    }
    [self comment];
    [self createData];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:0];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavigationLeftButton];
    [self p_play];
    self.view.backgroundColor = [UIColor whiteColor];
   
}
/*获取评论信息*/
- (void)createData {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"Dalvik/1.6.0 (Linux; U; Android 4.2.1; R823T Build/JOP40D) Liuda/2.2.0 (agent:s;channel:360;credential:e1MxMDIwMDAxMDF9LXsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzg2MzMzMTAyODY3NDU0Mn0teyMjIyMjIyMxNDczMTY0MTQyMDUyLTNjYWNiMTBlNGN9QDE0NzM0MDU5Nzc1MzY=;deviceId:863331028674542;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:4.2.1;idfa:null)" forHTTPHeaderField:@"User-Agent"];
    [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [manager.requestSerializer setValue:@"api.9liuda.com" forHTTPHeaderField:@"Host"];
    NSString *urlStr = [NSString stringWithFormat:@"http://211.151.51.100/v2/comment/list?engine=&messageId=%@&messageType=VIDEO&commentId=&cursor=0&count=10",_video.newsId];
    [manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        Model *mo = [Model modelWithDic:dic];
        _dataArray = [NSMutableArray arrayWithArray:mo.data];
        [_tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
}
/*评论*/
- (void)comment {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 240, kScreenWidth, kScreenHeight - 104) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerNib:[UINib nibWithNibName:@"CommitTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"1"];
    _tableView.rowHeight = 98;
    /*评论textField*/
    UIView *barView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 64, kScreenWidth, 64)];
    [self.view addSubview:barView];
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(60, 17, kScreenWidth - 128, 30)];
    [barView addSubview:_textField];
    _textField.placeholder = @"等你来吐槽";
    _textField.font = [UIFont systemFontOfSize:13];
    _textField.textColor = [UIColor lightGrayColor];
    _commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _commentBtn.frame = CGRectMake(_textField.frame.origin.x + _textField.frame.size.width, _textField.frame.origin.y, 40, 30);
    [barView addSubview:_commentBtn];
    _commentBtn.titleLabel.font = [UIFont systemFontOfSize:13];
//    _commentBtn.backgroundColor = [UIColor blackColor];
    [_commentBtn setTitleColor:[UIColor blackColor] forState:0];
    [_commentBtn setTitle:@"发送" forState:0];
    [_commentBtn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
}
/*发送评论*/
- (void)action:(UIButton *)btn {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [manager.requestSerializer setValue:@"Dalvik/1.6.0 (Linux; U; Android 4.2.1; R823T Build/JOP40D) Liuda/2.2.0 (agent:s;channel:360;credential:e1MxMDEwMDAxMDF9LXsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzg2MzMzMTAyODY3NDU0Mn0teyMjIyMjIyMxNDczMTU1OTc5ODA3LTQzNTkzYTY2M2R9QDE0NzI0MTc2MzEzMDE=;deviceId:863331028674542;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:4.2.1;idfa:null)" forHTTPHeaderField:@"User-Agent"];
    [manager.requestSerializer setValue:@"api.9liuda.com" forHTTPHeaderField:@"Host"];
    
    NSDictionary *parameters = @{@"content":_textField.text,
                                 @"messageId":_video.newsId,
                                 @"messageType":@"VIDEO",
                                 @"nickName":@"18304232468",
                                 @"portrait":@"http://meta.9liuda.com/image/user/icon/center_default_icon41.png"};
    [manager POST:@"http://api.9liuda.com/v1/comment/submit" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSDictionary *dic = responseObject;
        NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:parameters];
        [newDic setObject:@"0" forKey:@"totalLikeCount"];
        [newDic setObject:dic[@"attached"][@"createTime"] forKey:@"createTime"];
        DataModel *data = [DataModel modelWithDic:newDic];
        [_dataArray insertObject:data atIndex:0];
        [_tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
}
#pragma  mark - tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommitTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"1"];
    DataModel *data = _dataArray[indexPath.row];
    [cell.personImageView sd_setImageWithURL:[NSURL URLWithString:data.portrait]];
    cell.nickNameLabel.text = data.nickName;
    cell.countLoveLabel.text = [NSString stringWithFormat:@"%.0f",[data.totalLikeCount floatValue]];
    if ([cell.countLoveLabel.text isEqualToString:@"0"]) {
        cell.countLoveLabel.hidden = YES;
    }
    cell.messageLabel.text = data.content;
    cell.timeLabel.text = [self timeWithTimeIntervalString:[NSString stringWithFormat:@"%f",[data.createTime floatValue]]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma  mark - tableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 45)];
    view.backgroundColor = [UIColor lightGrayColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 45)];
    label.text = @"    全部评论";
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = [UIColor blackColor];
    [view addSubview:label];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 45;
}
/*时间戳转换成时间*/

- (NSString *)timeWithTimeIntervalString:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"MM-dd HH:mm"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
/**
 *  播放器
 */
- (void)p_play{
    self.playView = [FMGVideoPlayView videoPlayView];
    self.playView.delegate = self;
    _playView.index = 0;
    // 视频资源路径
    [_playView setUrlString:_video.mp4_url];
    // 播放器显示位置（竖屏时）
    _playView.frame = CGRectMake(0, 64, kScreenWidth, kScreenWidth/2);
    // 添加到当前控制器的view上
    [self.view addSubview:_playView];
    [_playView.player play];
    _playView.playOrPauseBtn.selected = YES;
    // 指定一个作为播放的控制器
    _playView.contrainerViewController = self;
    
    
}

#pragma mark - 懒加载代码
- (FullViewController *)fullVc
{
    if (_fullVc == nil) {
        _fullVc = [[FullViewController alloc] init];
    }
    return _fullVc;
}

- (void)leftBarButtonAction:(UIBarButtonItem *)sender{
    [_playView.player pause];
    [_playView.player setRate:0];
    _playView.playOrPauseBtn.selected = NO;
    

    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 视频代理方法

- (void)videoplayViewSwitchOrientation:(BOOL)isFull
{
    if (isFull) {
        
        [self.navigationController presentViewController:self.fullVc animated:NO completion:^{
            [self.fullVc.view addSubview:self.playView];
            _playView.center = self.fullVc.view.center;
            
            [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
                _playView.frame = self.fullVc.view.bounds;
                
                
            } completion:nil];
        }];
    } else {
        [self.fullVc dismissViewControllerAnimated:NO completion:^{
            [self.view addSubview:_playView];
            _playView.frame = CGRectMake(0,  64, kScreenWidth, (kScreenWidth-20)/2);
        }];
    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
// 自定义导航栏样式
- (void)initNavigationLeftButton {
    _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    _backBtn.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_backBtn];
    _backBtn.frame = CGRectMake(20, 20, 20, 20);
    [_backBtn setBackgroundImage:[UIImage imageNamed:@"Icon_jiantou"] forState:0];
    [_backBtn addTarget:self action:@selector(backToLoginAndRegisterViewController) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_backBtn];
    
    
}
// pop返回
- (void)backToLoginAndRegisterViewController {
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
